import React, { Component, Fragment } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'dva';
import { Modal, Form, Button, Select, Input, Radio, Badge, Spin, DatePicker } from 'antd';
import prompt from '@/components/Prompt';
import StandardTable from '@/components/StandardTable';
import SearchSelect from '@/components/SearchSelect';
import AdModal from '@/components/AdModal';
import moment from 'moment';
import AntdForm from '@/components/AntdForm';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import AntdDatePicker from '@/components/AntdDatePicker';
import AdUpload from '@/components/AdUpload';
import EditPage from '@/components/EditPage';
import IncidentalInfo from './IncidentalInfo';
import { checkStrLength, columnsDriver, columns1, columns2 } from '@/pages/Common/common';
import {
    queryDict,
    formItemFragement,
    filterAddFile,
    filterDeteteFile,
    formatPrice,
} from '@/utils/common';
import { allDictList } from '@/utils/constans';
import {
    allDispatchType,
    renderTableAdSelect,
    codes,
    trainType,
    selectArchivesList,
    DateMinus,
} from './utils';
import FileReader from '@/components/FileReader';
import DetailPage from '@/components/DetailPage';
const { Option } = Select;
const { TextArea } = Input;
const { confirm } = Modal;
const { MonthPicker } = DatePicker;

const dateFormat = 'YYYY-MM-DD HH:mm';
const dateFormatM = 'YYYY-MM-DD';

@connect(({ Archives, component, loading }) => ({
    dictObject: component.dictObject,
    trainInfoList: Archives.trainInfoList,
    trainInfoDetails: Archives.trainInfoDetails,
    incidentalInfoList: Archives.incidentalInfoList,
    loading: loading.effects[allDispatchType.trainInfoList],
    formValues: Archives.formValues,
}))
@Form.create()
export default class TrainNumInfo extends Component {
    state = {
        detailId: '',
        selectedRows: [],
        addSelectedRows: [],
        checkId: '',
        type: '',
        fileList: [],
        drivingType: 'LONG',
        incidentalData: {},
        drivers: [],
        cartHanging: [],
        showTips: false,
        required: {
            requiredCM: false,
        },
        vehicle: {
            cabinetType: '',
            cabinetCode: '',
        },
        driversFee: {},
        visibleSZTrainNo: false,
        trainNoSZList: [],
        startTime: '',
        endTime: '',
        cars: []
    };

    componentDidMount() {
        this.trainInfoList();
        this.setState({
            detailId: this.props.id,
        });
    }

    componentWillMount() {
        const allDict = [
            allDictList.currencyType,
            allDictList.archives_place,
            allDictList.otherFeeType,
            allDictList.cabinetType,
            allDictList.vehicleType,
            allDictList.archivesYCD_place
        ];
        queryDict({ props: this.props, allDict });
    }
    componentWillReceiveProps(nextProps, nextState) {
        const { visible, type } = nextProps;
        const { startMileage, checkId } = this.state;
        if (visible && checkId && type == 'add') {
            this.setState({
                checkId: '',
            });
        }
    }
    trainInfoList = (param = {}) => {
        const { id, dispatch } = this.props;
        param.id = id;
        dispatch({
            type: allDispatchType.trainInfoList,
            payload: {
                ...param,
            },
            callback: res => {
                const { trainInfoList } = this.props;
                let consumptionOil = 0;
                let totalFee = 0;
                let data = trainInfoList[id].list || [];
                if (data && data.length > 0) {
                    data.map(v => {
                        if (v.consumptionOil) consumptionOil += Number(v.consumptionOil);
                        if (v.totalFee) totalFee += Number(v.totalFee);
                    });
                    if (consumptionOil) consumptionOil.toFixed(2);
                    if (totalFee) totalFee.toFixed(2);
                    trainInfoList[id].list.push({ trainNo: '总计', consumptionOil: consumptionOil || 0, totalFee: totalFee || 0, shortBarge: 'last', });
                }

            },
        });
    };

    //详情
    showDetail = checkId => {
        const { dispatch, setTrainInfoModal } = this.props;
        this.handleStateChange([{ checkId }]);
        setTrainInfoModal && setTrainInfoModal('edit');

        //车次详情
        dispatch({
            type: allDispatchType.trainInfoDetails,
            payload: { id: checkId },
            callback: res => {
                const { driverTakes, driverIds, cabinetType, cabinetCode, type, cartHanging } = res;
                //计算单个车次司机提成小计：
                const driversFee = driverTakes.driverList;
                const driverObj = {
                    workerNo: '',
                    driverName: '总计',
                    rewardOilFee: driverTakes.rewardOilFee,
                    mileagePerformance: driverTakes.mileagePerformance,
                    timeAward: driverTakes.timeAward,
                    shortBargeSubsidies: driverTakes.shortBargeSubsidies,
                    pressureAmount: driverTakes.pressureAmount,
                    holidaySubsidies: driverTakes.holidaySubsidies,
                    totalFee: driverTakes.totalFee,
                };
                if (driverTakes.driverList && driverTakes.driverList.length > 0) {
                    driversFee.push(driverObj);
                }

                const driverIdObj = driverIds.map(v => {
                    return { id: v };
                });
                this.setState({
                    drivingType: type,
                    drivers: driverIdObj,
                    cartHanging: [{ id: cartHanging }],
                    vehicle: {
                        ...this.state.vehicle,
                        cabinetType,
                        cabinetCode,
                    },
                    driversFee: driversFee.length > 0 ? { list: driversFee } : {},
                });
            },
        });
    };
    handleCandle = () => {
        this.setState({
            visibleOperate: false,
        });
    };

    renderInfo = (text, record) => {
        const { mode } = this.props;
        const _text = renderTableAdSelect({ props: this.props, value: text, data: trainType });
        return (
            <AdButton
                mode="a"
                onClick={() => this.showDetail(record.id, record.status)}
                text={_text}
                code={codes.editTrain}
            />
        );
    };

    handleStateChange = (options = []) => {

        options.map(item => {
            this.setState(item);
        });
    };
    changeDrivingType(e) {
        const val = e.target.value
        const { form } = this.props;
        this.setState({
            drivingType: val
        })
    }

    //删除车次：
    delTrains = id => {
        const { dispatch, formValues, getArchivesDetails } = this.props;
        const { checkId } = this.state;
        confirm({
            title: '确定删除这条数据吗？',
            content: ' ',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: allDispatchType.deleteTrains,
                    payload: { id: checkId },
                    callback: data => {
                        this.modalOperate();
                        this.trainInfoList();
                        //刷新行车档案详情：
                        getArchivesDetails();
                        selectArchivesList({ props: this.props, payload: formValues });
                        checkId && this.getIncidentalList(checkId);
                    },
                });
            },
        });
    };

    handleOk = () => {
        const {
            dispatch,
            form,
            type,
            trainInfoDetails,
            getArchivesDetails,
            trainInfoList,
            incidentalInfoList,
            id,
            formValues,
            YCD
        } = this.props;
        const { drivingType, checkId, detailId, drivers, cartHanging,trainNo } = this.state;
        //1、校验车次
        form.validateFieldsAndScroll((err, values) => {
            const { transportStartTime, trainNo1, transit, transportEndTime, attaQuantity, ...value } = values;

            const startTime = transportStartTime ? moment(transportStartTime).format(dateFormat) : '';
            const endTime = transportEndTime ? moment(transportEndTime).format(dateFormat) : '';
            value.transportStartTime = startTime;
            value.transportEndTime = endTime;

            value.archivesNo = id; //档案id
            //附件：
            if (attaQuantity) {
                value.fileTokens = filterAddFile(attaQuantity);
            }
            //司机
            if (drivers.length > 0) {
                value.driverIds = drivers.map(v => {
                    return v.id;
                });
            } else {
                value.driverIds = [];
            }
            //中转地为空时 传空数据：
            value.transit = transit || ''

            if (checkId && trainInfoDetails[checkId]) {
                value.id = checkId;
                if (attaQuantity) {
                    value.deleteFileIds = filterDeteteFile(attaQuantity, trainInfoDetails[checkId].fileList);
                }
            }

            if (drivingType === 'EMPTY') {
                value.trainNo = trainNo || trainNo1;
            } else {
                value.trainNo = trainNo1 || trainNo;
            }
            console.log(drivingType,'trainNo----',trainNo,value.trainNo,trainNo1)
            //车挂：
            if (cartHanging.length > 0) {
                value.cartHanging = cartHanging[0].id;
            } else {
                value.cartHanging = '';
            }
            //2、校验杂费
            const infoForm = this.child.props.form;
            let relationVOS = [];
            infoForm.validateFieldsAndScroll(errors => {
                if (err || errors) return;
                const days = DateMinus(startTime, endTime);
                if (
                    startTime &&
                    endTime &&
                    days <= 0 &&
                    Number(value.startMileage) > Number(value.collectMileage)
                ) {
                    prompt({
                        content: '收车时间必须大于发车时间，收车里程必须大于发车里程！',
                        type: 'error',
                    });
                    return;
                }
                if (startTime && endTime && days <= 0) {
                    prompt({ content: '收车时间必须大于发车时间！', type: 'error' });
                    return;
                }
                if (Number(value.startMileage) > Number(value.collectMileage)) {
                    prompt({ content: '收车里程必须大于发车里程！', type: 'error' });
                    return;
                }
                if (checkId) {
                    relationVOS = incidentalInfoList[checkId].list.map(item => {
                        const { drivers, ...restd } = item;
                        if (item.id.includes('isNew')) {
                            const { id, ...rest } = restd;
                            return rest;
                        }
                        return restd;
                    });
                } else {
                    relationVOS =
                        Object.keys(incidentalInfoList).length > 0 ? incidentalInfoList[''].list : [];
                    relationVOS = incidentalInfoList[checkId].list.map(item => {
                        const { drivers, ...rest } = item;
                        return rest;
                    });
                }
                value.miscellaneousList = relationVOS; //杂费
                //console.log('一车队：YCD=>',YCD,allDispatchType.trainInfoOneTeamOperate,allDispatchType.trainInfoOperate)
                YCD ? value.type = 'NORMAL' : value.type
                console.log('value------------', value)
                dispatch({
                    //一车队  trainInfoOneTeamOperate 国内二车队 trainInfoOperate
                    type: YCD ? allDispatchType.trainInfoOneTeamOperate : allDispatchType.trainInfoOperate,
                    payload: value,
                    callback: data => {
                        this.trainInfoList();
                        //刷新行车档案详情：
                        getArchivesDetails();
                        selectArchivesList({ props: this.props, payload: formValues });
                        this.modalOperate();
                        checkId && this.getIncidentalList(checkId);
                        // this.child.incidentalInfoList(checkId, 'listShow');
                    },
                });
            });
        });
    };

    modalOperate = () => {
        const { setTrainInfoModal } = this.props;
        this.setState({
            fileList: [],
            // drivers: [],
            cartHanging: [],
            showTips: false,
            vehicle: {
                ...this.state.vehicle,
                cabinetType: '',
                cabinetCode: '',
            },
        });
        setTrainInfoModal();
    };

    /**
     * table 表格 分页操作
     */
    handleStandardTableChange = param => {
        const { detailId } = this.state;
        param.id = detailId;
        this.trainInfoList(param);
    };
    //杂费：
    expandedRowRender = (rec, index) => {
        const { type } = this.props;
        const { incidentalData, checkId } = this.state;
        return (
            <IncidentalInfo
                type="listShow"
                trainId={rec.id}
                onlyRead={true}
                countFee={rec.countFee}
                onRef={this.onRef}
                incidentalData={incidentalData}
            />
        );
    };
    onExpandRow = (expanded, record) => {
        if (expanded && record.countFee > 0) {
            this.getIncidentalList(record.id);
        }
    };

    getIncidentalList = id => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.incidentalInfoList,
            payload: { id },
            callback: data => {
                this.setState({
                    incidentalData: {
                        ...this.state.incidentalData,
                        [id]: { list: data || [] },
                    },
                });
            },
        });
    };
    addInfoInd = e => {
        e.stopPropagation();
        this.child.addInfoInd();
    };
    //移除杂费
    removeInfoInd = e => {
        e.stopPropagation();
        const { checkId, selectedRows } = this.state;
        const { incidentalInfoList } = this.props;
        const deleteIds = selectedRows.map(v => v.id);
        this.deleteInfoIds = selectedRows.filter(item => !item.id.includes('isNew')).map(v => v.id);
        const newData = incidentalInfoList[checkId].list.filter(item => !deleteIds.includes(item.id));
        this.saveAllValue({ incidentalInfoList: { [checkId]: { list: newData } } });
        this.handleStateChange([{ selectedRows: [], showTips: true }]);
    };
    onRef = ref => {
        this.child = ref;
    };
    saveAllValue = payload => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.value,
            payload: payload || {},
        });
    };
    getValue = (values, type) => {
        this.setState({
            [type]: values,
        });
        if (type === 'cartHanging') {
            this.change(values);
        }
    };

    //表格显示提示：
    showTipsFun = val => {
        this.setState({
            showTips: val,
        });
    };
    change = val => {
        this.setState({
            vehicle: {
                ...this.state.vehicle,
                cabinetType: val[0].cabinetType,
                cabinetCode: val[0].cabinetCode,
            },
        });
    };
    //选择车次号 ：
    showModalTrainNo = () => {
        const { form, vehicleNo } = this.props;
        const startTime = form.getFieldValue('transportStartTime');
        const endTime = form.getFieldValue('transportEndTime') || startTime;
        if (!vehicleNo) {
            prompt({
                content: '请先选择车牌号'
            })
            return
        }
        if (!startTime) {
            prompt({
                type: 'warn',
                content: '请选择发车时间'
            })
            return
        }
        this.setState({
            visibleSZTrainNo: true,
            startTime,
            endTime
        })
        this.getTrainNosToSZList()
    }

    modalSZ = () => {

        this.setState({
            cars: [],
            visibleSZTrainNo: false
        })
    }
    getTrainNosToSZList = () => {
        const { dispatch, form, vehicleNo } = this.props;
        const beginTime = form.getFieldValue('transportStartTime');
        const overTime = form.getFieldValue('transportEndTime') || beginTime;

        dispatch({
            type: allDispatchType.getTrainNosToSZ,
            payload: {
                beginTime: moment(beginTime).format(dateFormatM),
                overTime: moment(overTime).format(dateFormatM),
                vehicleNo
            },
            callback: (res) => {
                if (!res) return
                const data = res.map(v => {
                    return {
                        code: v,
                        value: v
                    }
                })
                this.setState({
                    trainNoSZList: data || []
                })
            }
        });
    }
    handleOkSZ = () => {
        const { form } = this.props;
        const transitSZ = form.getFieldValue('transitSZ');
        if (!transitSZ) {
            prompt({
                type: 'warn',
                content: '请选择车次'
            })
            return
        }
        form.setFieldsValue({ trainNo1: this.state.cars[0].shipmentNo });
        this.modalSZ()
    }

    render() {
        const {
            form: { getFieldDecorator },
            trainInfoList,
            trainInfoDetails,
            visible,
            loading,
            type,
            mode,
            status,
            dictObject,
            id,
            disabled,
            startMileage,
            isHK,
            YCD,
        } = this.props;
        // console.log('YCD========>>',YCD)
        const {
            checkId,
            fileList,
            drivingType,
            selectedRows,
            incidentalData,
            drivers,
            cartHanging,
            showTips,
            required: { requiredCM },
            vehicle: { cabinetType, cabinetCode },
            driversFee,
            visibleSZTrainNo,
            trainNoSZList,

        } = this.state;
        const trainDriversList = { list: [] };
        const detail = type === 'edit' && trainInfoDetails[checkId] ? trainInfoDetails[checkId] : {};
        const commonParams = {
            getFieldDecorator,
        };
        const isDetail = mode == 'detail' ? true : false;

        // console.log('trainInfoList', trainInfoList[id]);

        const InciTitle = (
            <span>
                杂费
                {showTips && (
                    <span style={{ color: 'red', marginLeft: 30 }}>当前数据有变化，请注意保存</span>
                )}
            </span>
        );

        const prefixSelector = (name, value) => (
            <AntdFormItem code={name} initialValue={value || undefined} {...commonParams}>
                <AdSelect
                    disabled={true}
                    data={dictObject[allDictList.currencyType]}
                    payload={{ code: allDictList.currencyType }}
                />
            </AntdFormItem>
        );

        const trainColumns = [
            {
                title: '序号',
                dataIndex: 'index',
                width: 60,
                render: (text, record, i) => {
                    const { trainInfoList, id } = this.props;
                    let data = trainInfoList[id].list || [];
                    if (data && data.length > 0 && i == data.length - 1) {
                        return '';
                    }
                    return <span style={{ marginLeft: 5 }}>{i + 1}</span>;
                },
            },
            {
                title: '类型',
                dataIndex: 'type',
                width: 80,
                render: (text, record) => this.renderInfo(text, record),
                // render: text => renderTableAdSelect({ props: this.props, value: text, data: trainType }),
            },
            {
                title: '车次号',
                dataIndex: 'trainNo',
                width: 100,
                render: text => {
                    return <span title={text}>{text}</span>;
                },
            },
            {
                title: '始发地',
                dataIndex: 'origin',
                width: 80,
                render: text => YCD ?
                    renderTableAdSelect({ props: this.props, value: text, key: allDictList.archivesYCD_place })
                    : renderTableAdSelect({ props: this.props, value: text, key: allDictList.archives_place })
            },
            {
                title: '中转地',
                dataIndex: 'transit',
                width: 80,
                render: text => YCD ?
                    renderTableAdSelect({ props: this.props, value: text, key: allDictList.archivesYCD_place })
                    : renderTableAdSelect({ props: this.props, value: text, key: allDictList.archives_place })
            },
            {
                title: '目的地',
                width: 80,
                dataIndex: 'destination',
                render: text => YCD ?
                    renderTableAdSelect({ props: this.props, value: text, key: allDictList.archivesYCD_place })
                    : renderTableAdSelect({ props: this.props, value: text, key: allDictList.archives_place })
            },

            {
                title: '司机',
                dataIndex: 'driverName',
                width: 100,
                render: text => {
                    return <span title={text}>{text}</span>;
                },
            },
            {
                title: '发车时间',
                dataIndex: 'transportStartTime',
                width: 120,
                render: text => {
                    return <span title={text}>{text}</span>;
                },
            },
            {
                title: '收车时间',
                dataIndex: 'transportEndTime',
                width: 120,
                render: text => {
                    return <span title={text}>{text}</span>;
                },
            },
            {
                title: '发车里程(KM)',
                width: 100,
                dataIndex: 'startMileage',
            },
            {
                title: '行驶里程(KM)',
                width: 100,
                dataIndex: 'travelMileage',
            },
            {
                title: '收车里程(KM)',
                width: 100,
                dataIndex: 'collectMileage',
            },
            {
                title: '分摊油耗量(L)',
                width: 100,
                dataIndex: 'consumptionOil',
                render: text => <span>{text || 0}</span>,
            },
            {
                title: '杂费总计',
                dataIndex: 'totalFee',
                render: text => <span>{formatPrice(text) || 0}</span>,
            },
        ];

        if (!YCD) {
            trainColumns.splice(3, 0, {
                title: '是否短驳',
                width: 80,
                dataIndex: 'shortBarge',
                render: text => {
                    return <span>{text == 'yes' ? '是' : (text == 'no' || text !== 'last' ? '否' : '')}</span>;
                },
            })
            trainColumns.push({
                title: '车挂',
                dataIndex: 'cartHangingName',
                width: 100,
            }, {
                title: '货重(KG)',
                width: 80,
                dataIndex: 'weight',
            }, {
                title: '柜型',
                dataIndex: 'cabinetType',
                width: 60,
                render: text =>
                    renderTableAdSelect({
                        props: this.props,
                        value: text,
                        key: allDictList.cabinetType,
                    }),
            }, {
                title: '柜号',
                dataIndex: 'cabinetCode',
                width: 100,
            }
            )
        }
        const formItem = [
            !YCD && [
                <AntdFormItem
                    label="类型"
                    code="type"
                    initialValue={drivingType}
                    rules={[{ required: !YCD }]}
                    {...commonParams}
                >
                    <Radio.Group
                        onChange={e => {
                            this.changeDrivingType(e);
                        }}
                        disabled={detail.type == 'EMPTY' || disabled}
                    >
                        <Radio value="LONG">
                        长途运输
                        </Radio>
                        <Radio value="SHORT">
                        短途运输
                        </Radio>
                        {type === 'edit' && drivingType === 'NORMAL' ?
                            <Radio value="NORMAL">
                                正常运输
                         </Radio>
                            : ''
                        }
                        <Radio value="EMPTY">
                            短途放空
                        </Radio>
                        <Radio value="LONGEMPTY">长途放空</Radio>
                        <Radio value="UNUSUAL">异常运输</Radio>
                    </Radio.Group>
                </AntdFormItem>,
                <AntdFormItem
                    label="时效奖"
                    code="shortBarge"
                    initialValue={detail.shortBarge || 'no'}
                    rules={[{ required: !YCD }]}
                    {...commonParams}
                >
                    <Radio.Group disabled={disabled}>
                        <Radio value="no" disabled={disabled}>有</Radio>
                        <Radio value="yes" disabled={disabled}>无</Radio>
                    </Radio.Group>
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="发车时间"
                    code="transportStartTime"
                    rules={[{ required: YCD ? false : true }]}
                    initialValue={
                        detail && detail.transportStartTime
                            ? moment(detail.transportStartTime, dateFormat)
                            : null
                    }
                    {...commonParams}
                >
                    <AntdDatePicker showTime disabled={disabled} />
                </AntdFormItem>,
                <AntdFormItem
                    label="收车时间"
                    code="transportEndTime"
                    initialValue={
                        detail && detail.transportEndTime ? moment(detail.transportEndTime, dateFormat) : null
                    }
                    {...commonParams}
                >
                    <AntdDatePicker showTime disabled={disabled} placeholder={isDetail ? '' : '请选择日期'} />
                </AntdFormItem>,
            ],
            [
                <span style={{ display: 'flex' }} className="cus-szFrom">
                    {
                       !YCD& drivingType !== 'LONG' && drivingType !== 'SHORT' ? (
                            <AntdFormItem
                                label="车次号"
                                code="trainNo1"
                                initialValue={ detail?.trainNo }
                                {...commonParams}
                                style={{ flex: 1 }}
                            >
                                <AntdInput disabled={true} placeholder="自动生成" />
                            </AntdFormItem>

                        ) : (!YCD&drivingType == 'SHORT' && !detail.type ?
                            <AntdFormItem
                                label="车次号"
                                code="trainNo1"
                                initialValue={detail?.trainNo}
                                {...commonParams}
                                style={{ flex: 1 }}
                            >
                                <AntdInput disabled={true} placeholder="自动生成" />
                            </AntdFormItem>
                            :
                            (!YCD?
                                <AntdFormItem
                                    label="车次号"
                                    code="trainNo1"
                                    initialValue={detail?.trainNo}
                                    {...commonParams}
                                    style={{ flex: 1 }}
                                >
                                    <AntdInput placeholder={isDetail ? '' : '请输入'} disabled={disabled} />
                                </AntdFormItem>
                                :
                                <AntdFormItem
                                    label="车次号"
                                    code="trainNo1"
                                    initialValue={detail?.trainNo}
                                    {...commonParams}
                                    style={{ flex: 1 }}
                                >
                                    <AntdInput placeholder={isDetail ? '' : '请输入'} disabled={false} />
                                </AntdFormItem>
                            )
                            )
                    }
                    <AdButton
                        mode="a"
                        onClick={() => this.showModalTrainNo()}
                        text="获取车次"
                        disabled={disabled}
                        style={{ marginLeft: 6, lineHeight: '30px' }}
                    // code={codes.editTrain}
                    />
                </span>,
                <AntdFormItem
                    label="司机"
                    code="driverIds"
                    initialValue={drivers}
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    <SearchSelect
                        dataUrl="tms/tms-driver-archives/selectDriverList"
                        url="tms/tms-driver-archives/selectDriverView_s"
                        multiple={true} // 是否多选
                        selectedData={drivers} // 选中值
                        columns={columnsDriver} // 表格展示列
                        onChange={val => this.getValue(val, 'drivers')} // 获取选中值
                        id="ArchivesOperate_2"
                        disabled={disabled}
                        allowClear={false}
                        // scrollX={350}
                        placeholder={isDetail ? '' : '请输入'}
                        payload={{ mdsCompanyId: YCD ? 'JS02' : 'JS0202' }}
                    />
                </AntdFormItem>,

            ],
            [
                !YCD && <AntdFormItem
                    label="车挂"
                    code="cartHanging"
                    initialValue={detail.cartHanging}
                    rules={[{ required: !YCD }]}
                    {...commonParams}
                >
                    <SearchSelect
                        dataUrl="tms/tms-vehicle/selectListByArchives" ///tms/tms-vehicle/selectListByArchives (二车队)
                        url="tms/tms-archives/selectVehicleView_s" // selectedData只有id时需要传url
                        selectedData={cartHanging} // 选中值
                        multiple={false} // 是否多选
                        showValue="cartPlateOneNo"
                        searchName="cartPlate"
                        columns={columns1} // 表格展示列
                        onChange={val => this.getValue(val, 'cartHanging')} // 获取选中值
                        scrollX={350}
                        disabled={disabled}
                        id="archiveslist_operate_1_0"
                        payload={{ categoryList: ['CAR-HANGING'] }}
                    />
                </AntdFormItem>,
                !YCD && <AntdFormItem
                    label="货重(KG)"
                    code="weight"
                    initialValue={detail.weight || 0}
                    rules={[{ required: !YCD }]}
                    {...commonParams}
                >
                    <AntdInput mode="money" disabled={disabled} placeholder={isDetail ? '' : '请输入'} />
                </AntdFormItem>,
            ],
            !YCD && [
                <AntdFormItem
                    label="柜型"
                    code="cabinetType"
                    rules={[{ required: !YCD }]}
                    initialValue={cabinetType}
                    {...commonParams}
                >
                    <AdSelect
                        isExist={true}
                        data={dictObject[allDictList.cabinetType]}
                        payload={{ code: allDictList.cabinetType }}
                        disabled={disabled}
                    />
                </AntdFormItem>,
                <AntdFormItem label="柜号" code="cabinetCode" initialValue={cabinetCode} {...commonParams}>
                    <AntdInput disabled={disabled} placeholder={isDetail ? '' : '请输入'} />
                </AntdFormItem>,
            ],

            [
                <AntdFormItem
                    label="始发地"
                    initialValue={detail.origin}
                    rules={[{ required: true }]}
                    code="origin"
                    {...commonParams}
                >
                    {YCD ?
                        <AdSelect
                            data={dictObject[allDictList.archivesYCD_place]}
                            payload={{ code: allDictList.archivesYCD_place }}
                            disabled={disabled}
                        /> :
                        <AdSelect
                            data={dictObject[allDictList.archives_place]}
                            payload={{ code: allDictList.archives_place }}
                            disabled={disabled}
                        />
                    }
                </AntdFormItem>,
                <AntdFormItem
                    label="目的地"
                    initialValue={detail.destination}
                    rules={[{ required: true }]}
                    code="destination"
                    {...commonParams}
                >
                    {YCD ?
                        <AdSelect
                            data={dictObject[allDictList.archivesYCD_place]}
                            payload={{ code: allDictList.archivesYCD_place }}
                            disabled={disabled}
                        /> :
                        <AdSelect
                            data={dictObject[allDictList.archives_place]}
                            payload={{ code: allDictList.archives_place }}
                            disabled={disabled}
                        />
                    }
                    {/* <AdSelect
                        disabled={disabled}
                        data={dictObject[allDictList.archives_place]}
                        payload={{ code: allDictList.archives_place }}
                    /> */}
                </AntdFormItem>,],
            [
                !YCD && <AntdFormItem label="中转地" initialValue={detail.transit} code="transit" {...commonParams}>
                    <AdSelect
                        disabled={disabled}
                        data={dictObject[allDictList.archives_place]}
                        payload={{ code: allDictList.archives_place }}
                    />
                </AntdFormItem>,
                <></>
            ],

            [
                <AntdFormItem
                    label="发车里程(KM)"
                    rules={[{ required: YCD ? false : true }]}
                    code="startMileage"
                    initialValue={detail.startMileage || startMileage}
                    {...commonParams}
                >
                    <AntdInput mode="money" disabled={disabled} />
                </AntdFormItem>,
                <AntdFormItem
                    label="收车里程(KM)"
                    code="collectMileage"
                    initialValue={detail.collectMileage}
                    rules={[{ required: requiredCM }]}
                    {...commonParams}
                >
                    <AntdInput mode="money" disabled={disabled} placeholder={isDetail ? '' : '请输入'} />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="行驶里程(KM)"
                    code="travelMileage"
                    initialValue={detail.travelMileage || ''}
                    {...commonParams}
                >
                    <AntdInput disabled={true} placeholder="" />
                </AntdFormItem>,
                <AntdFormItem
                    label="行驶时长"
                    code="travelTime"
                    initialValue={detail.travelTime || ''}
                    {...commonParams}
                >
                    <AntdInput disabled={true} placeholder="" />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="备注"
                    code="remarks"
                    rules={[
                        {
                            validator: (rule, value, callback) => {
                                checkStrLength(rule, value, callback, 500, '备注');
                            },
                        },
                    ]}
                    initialValue={detail.remarks}
                    {...commonParams}
                >
                    <AntdInput
                        maxlen={500}
                        disabled={disabled}
                        type="textarea"
                        placeholder={isDetail ? '' : '请输入不超过500字符'}
                    />
                </AntdFormItem>,
                YCD && <AntdFormItem
                    label="结算周期"
                    code="settlement_date"
                    rules={[{ required: false }]}
                    initialValue={detail.settlement_date ? moment(detail.settlement_date, dateFormatM)
                        : moment(new Date(), dateFormatM)
                    }
                    {...commonParams}
                >
                    <MonthPicker disabled={disabled} style={{ width: "100%" }} />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="附件"
                    code="attaQuantity"
                    initialValue={detail.fileList || []}
                    {...commonParams}
                >
                    <FileReader urlType="tms" disabled={disabled} showUpload={isDetail ? false : true} />
                </AntdFormItem>,
            ],
        ];

        const formItemTrial = [
            [
                <DetailPage label="油耗标准(升/百公里)" value={formatPrice(detail.fuelStandards)} />,
                <DetailPage label="节省油量(升)" value={detail.saveFuel} />,
            ],
            [
                <DetailPage label="里程绩效提成(元/公里)" value={detail.mileageBilling} />,
                <DetailPage label="时效达标奖(元/次)" value={detail.timeBased} />,
            ],
            [
                <DetailPage label="短驳补助(次)" value={detail.shortBargeSubsidies} />,
                <DetailPage label="压车补助" value={detail.pressurePrice} />,
            ],
            [
                <DetailPage label="节假日津贴(元/天)" value={detail.holidaySubsidies} />,
                <DetailPage label="节假日天数" value={detail.holidayDays} />,
            ],
        ];
        const editPageParams = {
            title: detail.trainNo || '新增车次',
            // headerOperate: this.headerOperate(),
            panelValue: [
                { key: '基础信息' },
                {
                    key: InciTitle,
                    extra: (
                        <div style={{ display: mode == 'detail' ? 'none' : 'block' }}>
                            <AdButton
                                onClick={e => {
                                    this.removeInfoInd(e);
                                }}
                                ghost
                                disabled={disabled || selectedRows.length === 0}
                                text="移除"
                                type="danger"
                            />
                            <AdButton
                                type="primary"
                                disabled={disabled}
                                onClick={e => {
                                    this.addInfoInd(e);
                                }}
                                style={{ marginLeft: 8 }}
                                text="添加"
                            />
                        </div>
                    ),
                },
                // checkId && { key: '计费标准' },
                // checkId && { key: '司机提成' },
            ],
        };
        let cusFooter = [
            <AdButton text="取消" key="back" onClick={() => this.modalOperate()} />,
            <AdButton
                text="保存"
                key="submit"
                type="primary"
                loading={loading}
                onClick={this.handleOk}
            />,
        ];
        if (type == 'edit') {
            cusFooter.splice(
                0,
                0,
                <AdButton text="删除" type="danger" ghost key="custom" onClick={() => this.delTrains()} />
            );
        }
        const showFooter =
            mode == 'detail'
                ? { footer: null }
                : {
                    footer: cusFooter,
                };


        const formItemTrainNo = [
            // [
            //     <AntdFormItem label="时间" code="trainNoTime" {...commonParams}>
            //         <AntdDatePicker mode="range" onChange={this.getTrainNosToSZ} />
            //     </AntdFormItem>,
            // ],
            [<AntdFormItem label="车次" initialValue="" code="transitSZ" {...commonParams}>
                {/* <AdSelect
                    data={trainNoSZList}
                    isExist={true}
                /> */}

                <SearchSelect
                    dataUrl="tms/tms-archives/getTrainNosToSZ"
                    // url="tms/tms-oil/selectOilVehicleView_s" // selectedData只只有id时需要传url
                    selectedData={this.state.cars} // 选中值
                    multiple={false} // 是否多选
                    showValue="shipmentNo"
                    // searchName="cartPlate"
                    columns={columns2} // 表格展示列
                    onChange={values => { console.log('values', values), this.setState({ cars: values }) }} // 获取选中值
                    scrollX={480}
                    id="lineId"
                    allowClear={true}
                    payload={{ vehicleNo: this.props.vehicleNo, beginTime: moment(this.state.startTime).format(dateFormatM), overTime: moment(this.state.endTime).format(dateFormatM) }} //筛选为整车和车头的
                />

            </AntdFormItem>]
        ]
        return (
            <Fragment>
                <StandardTable
                    disabledRowSelected={true}
                    loading={loading}
                    data={trainInfoList[id] || {}}
                    code="cus"
                    columns={trainColumns}
                    onPaginationChange={this.handleStandardTableChange}
                    expandedRowRender={this.expandedRowRender}
                    onExpandRow={this.onExpandRow}
                    className="table_info_total"
                />
                {visible && (
                    <AdModal
                        visible={visible}
                        title={mode == 'detail' ? '车次详情' : type == 'edit' ? '编辑车次' : '新增车次'}
                        onOk={this.handleOk}
                        okButtonProps={{ disabled }}
                        onCancel={() => {
                            this.modalOperate();
                        }}
                        okText="保存"
                        width="80%"
                        bodyStyle={{
                            height: 'calc(100vh - 130px)',
                            overflowY: 'auto',
                            padding: '10px 24px',
                        }}
                        {...showFooter}
                    >
                        <EditPage {...editPageParams}>
                            <Spin spinning={id ? loading : false}>
                                <AntdForm>{formItemFragement(formItem)}</AntdForm>
                            </Spin>
                            <Fragment>
                                <IncidentalInfo
                                    trainId={checkId}
                                    onlyRead={mode == 'detail' ? true : false}
                                    onRef={this.onRef}
                                    selectedRows={selectedRows}
                                    disabled={disabled}
                                    onSelectRow={selectedRows => this.handleStateChange([{ selectedRows }])}
                                    showTipsFun={this.showTipsFun}
                                />
                            </Fragment>
                        </EditPage>
                    </AdModal>
                )}

                {visibleSZTrainNo && (
                    <AdModal
                        visible={visibleSZTrainNo}
                        title="选择车次"
                        onOk={this.handleOkSZ}
                        onCancel={() => {
                            this.modalSZ();
                        }}
                        okText="保存"
                        width="600px"
                        bodyStyle={{
                            height: '200px',
                            overflowY: 'auto',
                            padding: '20px 0px',
                            paddingRight: "80px"
                        }}
                    >
                        {/* <div style={{ color: 'red', marginBottom: 15 }}>提示：先选择时间，再选择车次</div> */}
                        <AntdForm>{formItemFragement(
                            formItemTrainNo
                        )}
                        </AntdForm>

                    </AdModal>
                )}
            </Fragment>
        );
    }
}
